<template>
    <div class="">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="iconfont icon-wenzhangliebiaoxiangqing"></i>文章管理</el-breadcrumb-item>
                <el-breadcrumb-item>编辑文章</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form ref="articleForm" :model="form" :rules="rules" label-width="80px">
                <el-form-item prop="title" label="文章标题" >
                    <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>
                </el-form-item>
                <el-form-item prop="keywords" label="关键字">
                    <el-input v-model="form.keywords" placeholder="请输入文章的关键字"></el-input>
                </el-form-item>
                <el-form-item prop="description" label="文章描述">
                    <el-input type="textarea" placeholder="请输入文章描述" v-model="form.description"></el-input>
                </el-form-item>
                <el-form-item label="文章图片" prop="image">
                    <div class="img-upload">
                        <el-upload
                                accept="image/*"
                                class="avatar-uploader"
                                action="/admin/oss_upload"
                                :headers="header"
                                :before-remove="beforeRemove"
                                :on-preview="handlePictureCardPreview"
                                :on-success="handleAvatarSuccess"
                                :file-list="fileList"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item prop="enabled" label="立即发布">
                    <el-switch
                            v-model="form.enabled"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
                <el-form-item prop="classify_id" label="文章分类" >
                    <el-radio-group v-model="form.classify_id">
                        <el-radio  :key="index" :label="item.id" v-for="(item,index) in resource">{{item.name}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="文章内容" prop="content">
                    <!-- bidirectional data binding（双向数据绑定） -->
                    <quill-editor v-model="form.content"
                                  ref="myQuillEditor"
                                  :options="editorOption"
                                  @blur="onEditorBlur($event)"
                                  @focus="onEditorFocus($event)"
                                  @ready="onEditorReady($event)"
                                  @change="onEditorChange($event)"
                    >
                    </quill-editor>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit('articleForm')">保存修改</el-button>
                    <el-button @click="onResetForm('articleForm')">重置内容</el-button>
                </el-form-item>
            </el-form>

            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
        </div>
    </div>
</template>

<script>
    // require styles
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import { quillEditor } from 'vue-quill-editor'
    export default {
        name: "add-article",
        props:{
          article_id:{
              type:Number,
              default:0
          }
        },
        data(){
            return {
                form: {
                    title: '',
                    keywords: '',
                    description: '',
                    image: '',
                    classify_id: '',
                    enabled: true,
                    content:''
                },
                fileList:[],
                resource: [],
                imageUrl: '',
                header:{
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'baseUrl':'/'
                },
                editorOption:{},
                dialogImageUrl: '',
                dialogVisible: false,
                rules:{
                    title:[
                        {required:true,message:'请输入文章标题',trigger:'blur'},
                    ],
                    keywords:[
                        {required:true,message:'请输入文章的关键字',trigger:'blur'}
                    ],
                    description:[
                        {required:true,message:'请输入文章的描述',trigger:'blur'}
                    ],
                    content:[
                        {required:true,message:'请编辑文章的内容',trigger:'blur'}
                    ],
                    enabled:[
                        {required:true,message:'请选择是否可用',trigger:'change'}
                    ],
                    image:[
                        {required:true,message:'请上传文章缩略图',trigger:'change'}
                    ],
                    classify_id:[
                        {required:true,message:'请选择文章分类',trigger:'change'}
                    ]
                }
            }
        },
        components:{
            quillEditor
        },
        mounted(){

        },
        created(){
            this._get_tag_classify();
            this._init_article(this.article_id);
        },
        methods:{
            _get_tag_classify(){
                this.getAjax('admin/first_level').then((res)=>{
                    if(res.code ==1){
                        this.resource = res.data;
                    }
                })
            },
            _init_article(id){
                this.getAjax('admin/get_specific_article',{article_id:id}).then((res)=>{
                    if(res.code == 1){
                        this.form = res.data;
                        this.form.title = res.data.title;
                        this.form.keywords = res.data.keywords;
                        this.form.description = res.data.description;
                        this.form.content = res.data.content;
                        this.form.classify_id = res.data.classify_id;
                        this.imageUrl = res.data.image;
                        this.fileList.push({name:this.imageUrl,url:this.imageUrl});
                        this.form.enabled = res.data.enabled ? true : false;
                    }
                })
            },
            onResetForm(formName){  //重置表单
                this.$refs[formName].resetFields();
            },
            onSubmit(formName) {  //表单提交加验证
                this.$refs[formName].validate((valid,obj) => {
                    if (valid) {
                       this.postAjax('admin/edit_article',{...this.form,article_id:this.article_id}).then(res=>{
                           if(res.code===1){
                               this.$message.success(res.msg);
                               this.$emit('EditArticleSuccess');
                           }
                       })
                    } else {
                        let test = Object.values(obj);
                        this.$message({
                            message: test[0][0].message,
                            type: 'warning'
                        });
                        return false;
                    }
                });
            },
            handlePictureCardPreview(file){
                this.dialogImageUrl = file.response.data.path;
                this.dialogVisible = true;
            },
            handleAvatarSuccess(res, file,fileList) {
                this.imageUrl = URL.createObjectURL(file.raw);
                if(res.code == 1){
                    if(fileList.length>=2){
                        fileList.shift();
                    }
                    this.$message.success(res.msg);
                    this.form.image = res.url;
                }else{
                    this.$message.error(res.msg);
                }
            },
            beforeRemove(file, fileList){
                return this.$confirm(`确定移除 ${ file.name }？`,'温馨提示',{
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((res)=>{
                    this.imageUrl = '';
                    this.form.image = '';
                });
            },
            beforeAvatarUpload(file) {
                console.log(file);
                const isJPG = file.type === 'image/jpeg' || file.type==='image/png' || file.type==='image/gif';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传文件格式只能是图片类型!');
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            onEditorBlur(quill) {//失去焦点事件

            },
            onEditorFocus(quill) {//获得焦点事件//
            },
            onEditorReady(quill) { //vue-quill-editor初始化之后事件
            },
            onEditorChange({ quill, html, text }) { //编辑器内容改变事件
                // this.form.content = html
            }
        },
        watch:{

        }
    }
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }
    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }
</style>